const axios = require('axios');

class TencentStockService {
  constructor() {
    // 腾讯股票API基础URL
    this.baseUrl = 'https://proxy.finance.qq.com';
    
    // 股票代码与名称的映射关系（实际应用中可能需要从数据库或其他API获取）
    this.stockNames = {
      '000001': '平安银行',
      '600000': '浦发银行',
      '600036': '招商银行',
      '600519': '贵州茅台',
      '000858': '五粮液',
      '000002': '万科A',
      '601318': '中国平安',
      '000333': '美的集团',
      '600030': '中信证券',
      '601166': '兴业银行'
      // 可以根据需要添加更多股票代码和名称的映射
    };
  }

  // 转换股票代码格式以适配腾讯API
  convertSymbolForTencent(symbol) {
    // 检查symbol是否定义
    if (!symbol) {
      throw new Error('symbol is not defined');
    }
    
    console.log(`Converting symbol for Tencent: ${symbol}`);
    
    // 中国A股市场代码转换
    if (symbol.startsWith('000') || symbol.startsWith('002') || symbol.startsWith('300')) {
      // 深圳证券交易所股票
      const converted = 'sz' + symbol;
      console.log(`Converted ${symbol} to ${converted} (Shenzhen) for Tencent`);
      return converted;
    } else if (symbol.startsWith('600') || symbol.startsWith('601') || symbol.startsWith('603') || symbol.startsWith('688')) {
      // 上海证券交易所股票
      const converted = 'sh' + symbol;
      console.log(`Converted ${symbol} to ${converted} (Shanghai) for Tencent`);
      return converted;
    }
    
    // 其他代码保持不变
    console.log(`Keeping ${symbol} unchanged for Tencent`);
    return symbol;
  }

  // 根据股票代码获取股票名称
  getStockNameBySymbol(symbol) {
    // 优先从映射表中获取名称
    if (this.stockNames[symbol]) {
      return this.stockNames[symbol];
    }
    
    // 如果映射表中没有，返回默认名称
    return `股票${symbol}`;
  }

  // 获取多只股票的实时数据
  async getMultipleStocks(symbols) {
    try {
      const results = [];
      
      // 由于腾讯API的限制，我们需要逐个获取每只股票的数据
      for (const symbol of symbols) {
        try {
          const stockData = await this.getRealTimeData(symbol);
          results.push(stockData);
        } catch (error) {
          console.error(`Error fetching data for ${symbol}:`, error.message);
          // 即使某只股票获取失败，也继续处理其他股票
          results.push({
            symbol: symbol,
            name: this.getStockNameBySymbol(symbol),
            error: error.message
          });
        }
      }
      
      return results;
    } catch (error) {
      console.error(`Error fetching multiple stocks data:`, error.message);
      throw new Error(`Error fetching multiple stocks data: ${error.message}`);
    }
  }

  // 获取股票历史数据
  async getHistoricalData(symbol, interval = 'daily') {
    try {
      const convertedSymbol = this.convertSymbolForTencent(symbol);
      console.log(`Fetching historical data from Tencent for ${symbol} (converted to ${convertedSymbol})`);
      
      // 腾讯API需要的参数
      const url = `${this.baseUrl}/ifzqgtimg/appstock/app/kline/kline?param=${convertedSymbol},day,,,300,&r=0.123456`;
      
      const response = await axios.get(url, {
        timeout: 15000 // 15秒超时
      });

      // 检查响应数据
      if (!response.data) {
        throw new Error('No data returned from Tencent API');
      }
      
      // 检查是否有错误信息
      if (response.data.code !== 0) {
        throw new Error(`Tencent API error: ${response.data.msg || 'Unknown error'}`);
      }

      const rawData = response.data.data?.[convertedSymbol]?.day || [];
      if (!rawData || !Array.isArray(rawData) || rawData.length === 0) {
        throw new Error('No historical data returned from Tencent API');
      }

      // 转换腾讯API的数据格式为统一格式
      const historicalData = rawData.map(item => {
        // 腾讯的数据格式: [日期, 开盘价, 收盘价, 最高价, 最低价, 成交量, 金额]
        if (!item[0] || item[1] === undefined || item[2] === undefined || 
            item[3] === undefined || item[4] === undefined || item[5] === undefined) {
          console.warn('Skipping invalid data item from Tencent:', item);
          return null;
        }
        
        return {
          date: item[0], // 日期格式 'YYYY-MM-DD'
          open: parseFloat(item[1]),
          close: parseFloat(item[2]),
          high: parseFloat(item[3]),
          low: parseFloat(item[4]),
          volume: parseInt(item[5])
        };
      }).filter(item => item !== null); // 过滤掉无效数据

      if (historicalData.length === 0) {
        throw new Error('No valid historical data after processing from Tencent API');
      }

      // 按日期排序（从旧到新）
      historicalData.sort((a, b) => new Date(a.date) - new Date(b.date));

      console.log(`Successfully fetched ${historicalData.length} records from Tencent for ${symbol}`);
      return historicalData;
    } catch (error) {
      console.error(`Error fetching historical data from Tencent for ${symbol}: ${error.message}`);
      // 如果是网络错误或超时，提供更具体的错误信息
      if (error.code === 'ECONNABORTED' || error.code === 'ENOTFOUND') {
        throw new Error(`Network error when fetching from Tencent: ${error.message}`);
      }
      throw new Error(`Error fetching historical data from Tencent: ${error.message}`);
    }
  }

  // 获取股票实时数据
  async getRealTimeData(symbol) {
    try {
      const convertedSymbol = this.convertSymbolForTencent(symbol);
      console.log(`Fetching real-time data from Tencent for ${symbol} (converted to ${convertedSymbol})`);
      
      // 腾讯实时行情API
      const url = `${this.baseUrl}/ifzqgtimg/appstock/app/newkline/newkline?param=${convertedSymbol},minute,,,1,&r=0.123456`;
      
      const response = await axios.get(url, {
        timeout: 10000 // 10秒超时
      });

      // 检查响应数据
      if (!response.data) {
        throw new Error('No data returned from Tencent API');
      }
      
      // 检查是否有错误信息
      if (response.data.code !== 0) {
        throw new Error(`Tencent API error: ${response.data.msg || 'Unknown error'}`);
      }

      const data = response.data.data?.[convertedSymbol]?.qt?.[convertedSymbol];
      if (!data) {
        throw new Error('No real-time data returned from Tencent API');
      }

      // 转换腾讯API的数据格式为统一格式
      return {
        symbol: symbol, // 返回原始符号
        name: this.getStockNameBySymbol(symbol), // 添加股票名称
        open: parseFloat(data[1] || 0),
        high: parseFloat(data[3] || 0),
        low: parseFloat(data[4] || 0),
        price: parseFloat(data[3] || 0), // 使用最高价作为当前价格
        volume: parseInt(data[6] || 0),
        latestTradingDay: new Date().toISOString().split('T')[0],
        previousClose: parseFloat(data[9] || 0),
        change: parseFloat(data[3] || 0) - parseFloat(data[9] || 0),
        changePercent: data[10] ? parseFloat(data[10]) : 0
      };
    } catch (error) {
      console.error(`Error fetching real-time data from Tencent for ${symbol}: ${error.message}`);
      // 如果是网络错误或超时，提供更具体的错误信息
      if (error.code === 'ECONNABORTED' || error.code === 'ENOTFOUND') {
        throw new Error(`Network error when fetching from Tencent: ${error.message}`);
      }
      throw new Error(`Error fetching real-time data from Tencent: ${error.message}`);
    }
  }
}

module.exports = new TencentStockService();